import { MessageBox } from 'element-ui'
import { dateFormat as df } from '@vimi/utils-tool'
import ImgPreview from '@/common/components/ImgPreview/ctor'
import ImgViewer from '@/common/components/ImgPreview/viewer'

/**
 * https://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/
 * @param {Promise} pm
 * @returns {Promise<T | *[]>}
 */
export const promise = pm => {
  return pm.then(data => [data, null]).catch(err => [undefined, err])
}

/**
 * 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
 * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
 * 例子：
 * this.$utils.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss.S') ==> 2006-07-02 08:09:04.423
 * this.$utils.dateFormat(new Date(), 'yyyy-M-d h:m:s.S')      ==> 2006-7-2 8:9:4.18
 * @param {String | Date} date 时间Date对象或字符串
 * @param {String} fmt 格式字符串
 */
export const dateFormat = df

/**
 * 从值中反回查找Key值
 * @param {Object} obj 对象
 * @param {String} value 需要查找的值
 * @param {String} defaultValue 找不到时默认的值
 */
export const findKeyFromValue = (obj, value = '', defaultValue = '') => {
  for (const k of Object.keys(obj)) {
    if (obj[k] === value) {
      return k
    }
  }
  return defaultValue
}

export const msgbox = options =>
  new Promise((resolve, reject) => {
    const {
      title = '提示',
      message = `确定?`,
      showCancelButton = true,
      confirmButtonText = '确定',
      cancelButtonText = '取消',
      confirmButtonLodingText = '操作中...',
      beforeClose = () => {},
      ...rest
    } = options
    MessageBox({
      title,
      message,
      showCancelButton,
      confirmButtonText,
      cancelButtonText,
      ...rest,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonText = confirmButtonLodingText
          instance.confirmButtonLoading = true

          const after = (success, res) => {
            instance.confirmButtonLoading = false
            instance.confirmButtonText = confirmButtonText

            if (success) {
              resolve(res)
              done()
            } else {
              reject(res)
            }
          }

          const bf = beforeClose()
          if (bf && bf.then) {
            bf.then(res => {
              after(true, res)
            }).catch(err => {
              after(false, err)
            })
          } else {
            after(true, bf)
          }
        } else {
          done()
        }
      },
    }).catch(err => {
      if (err !== 'cancel') throw err
    })
  })

export const preview = ImgPreview
export const viewer = ImgViewer
